#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json


def count_specific_spans(json_data):
    """
    统计满足条件的子JSON对象数量
    :param json_data: 包含JSON数据的字符串或文件路径
    :return: 满足条件的对象数量
    """
    if not json_data:
        return 0

    try:
        if isinstance(json_data, str) and json_data.endswith('.json'):
            with open(json_data, 'r', encoding='utf-8') as file:
                data = json.load(file)
        else:
            data = json.loads(json_data) if isinstance(json_data, str) else json_data

        if not isinstance(data, dict):
            return 0

        spans = data.get("data", {}).get("trace", {}).get("spans", [])
        if not isinstance(spans, list):
            return 0

        return sum(
            1 for span in spans
            if span.get("endpointName") == "Druid/Connection/getConnection"
            and span.get("serviceCode") == "car-core"
        )

    except (FileNotFoundError, json.JSONDecodeError, KeyError, AttributeError):
        return 0



# 示例用法
if __name__ == "__main__":


    # 方式2：从JSON文件读取
    try:
        result = count_specific_spans("/Users/zxh/Documents/临时/New_6.json")  # 替换为实际文件路径
        print(f"从文件读取的统计结果: {result}")
    except FileNotFoundError:
        print("错误：JSON文件未找到")
    except json.JSONDecodeError:
        print("错误：JSON格式解析失败")